package com.k4rthik.clipall.network;

import com.k4rthik.clipall.network.profile.Profile;
import com.k4rthik.clipall.network.profile.ProfileManager;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * Created by IntelliJ IDEA.
 * User: k4rthik
 * Date: 3/25/12
 * Time: 2:41 PM
 */

public class NetworkOps
{
    public static void sendClipboardText(String clipText) throws IOException
    {
        ProfileManager profileManager = ProfileManager.getInstance();
        Profile activeProfile = profileManager.getProfileById(profileManager.getActiveProfileId());

        if(activeProfile != null) {
            List<UUID> activeConnections = activeProfile.getConnectionIds();
            Iterator<UUID> connIt = activeConnections.iterator();

            while(connIt.hasNext()) {
                UUID thisUUID = connIt.next();
                Socket clientConnection = Connections.getClientConnections().get(thisUUID);
                Socket serverConnection = Connections.getServerConnections().get(thisUUID);

                if(clientConnection != null) {
                    PrintWriter socketWriter = new PrintWriter(clientConnection.getOutputStream(), true);
                    socketWriter.write(clipText);
                } else if (serverConnection != null){
                    PrintWriter socketWriter = new PrintWriter(serverConnection.getOutputStream(), true);
                    socketWriter.write(clipText);
                }
            }
        }
    }
}
